package com.sky.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;

@Service
public class ReportServiceImpl implements ReportService {
    private static final String PARAM_BEGIN_TIME = "begin";
    private static final String PARAM_END_TIME = "end";
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    private List<LocalDate> getBetweenDays(LocalDate begin, LocalDate end) {
        List<LocalDate> result = new ArrayList<>();
        for (; !begin.isAfter(end); begin = begin.plusDays(1)) {
            result.add(begin);
        }
        return result;
    }

    private Map<String, Object> buildDateRangeMap(LocalDateTime begin, LocalDateTime end) {
        Map<String, Object> map = new HashMap<>();
        map.put(PARAM_BEGIN_TIME, begin);
        map.put(PARAM_END_TIME, end);
        return map;
    }

    private LocalDateTime getDayStart(LocalDate date) {
        return LocalDateTime.of(date, LocalTime.MIN);
    }

    private LocalDateTime getDayEnd(LocalDate date) {
        return LocalDateTime.of(date, LocalTime.MAX);
    }

    /**
     * 获取营业额统计数据
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        // 算日期
        List<LocalDate> dateList = getBetweenDays(begin, end);

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = getDayStart(date);
            LocalDateTime endTime = getDayEnd(date);
            Map<String, Object> map = buildDateRangeMap(beginTime, endTime);
            map.put("status", Orders.COMPLETED);
            // 如果为空就转为0.0
            Double turnover = Optional.ofNullable(orderMapper.sumByMap(map)).orElse(0.0);
            turnoverList.add(turnover);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 获取用户统计数据
     * 
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getBetweenDays(begin, end);
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        for (int i = 0; i < dateList.size(); ++i) {
            LocalDate date = dateList.get(i);
            LocalDateTime beginTime = getDayStart(date);
            LocalDateTime endTime = getDayEnd(date);
            Map<String, Object> map = buildDateRangeMap(beginTime, endTime);

            Integer newUserCount = Optional.ofNullable(userMapper.countByMap(map)).orElse(0);
            newUserList.add(newUserCount);
            // 总用户数等于前一条用户数 + 这一天新用户数
            if (i == 0) {
                map.remove(PARAM_BEGIN_TIME);
                Integer totalUserCount = Optional.ofNullable(userMapper.countByMap(map)).orElse(0);
                totalUserList.add(totalUserCount);
            } else {
                totalUserList.add(totalUserList.get(i - 1) + newUserCount);
            }
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 获取订单统计数据
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getBetweenDays(begin, end);
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = getDayStart(date);
            LocalDateTime endTime = getDayEnd(date);
            Map<String, Object> map = buildDateRangeMap(beginTime, endTime);
            Integer orderCount = Optional.ofNullable(orderMapper.countByMap(map)).orElse(0);
            orderCountList.add(orderCount);
            totalOrderCount += orderCount;
            map.put("status", Orders.COMPLETED);
            Integer validCount = Optional.ofNullable(orderMapper.countByMap(map)).orElse(0);
            validOrderCountList.add(validCount);
            validOrderCount += validCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(totalOrderCount == 0 ? 0.0 : validOrderCount.doubleValue() / totalOrderCount)
                .build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = getDayStart(begin);
        LocalDateTime endTime = getDayEnd(end);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(salesTop10.stream().map(GoodsSalesDTO::getName).toArray(), ","))
                .numberList(StringUtils.join(salesTop10.stream().map(GoodsSalesDTO::getNumber).toArray(), ","))
                .build();
    }

    /**
     * 导出数据
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 查询数据库获取数据
        LocalDate toDay = LocalDate.now();
        LocalDate beginDate = toDay.minusMonths(1);
        LocalDate endDate = toDay.minusDays(1);
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(
                LocalDateTime.of(beginDate, LocalTime.MIN),
                LocalDateTime.of(endDate, LocalTime.MAX));
        // 读取模板文件 创建流对象
        try (
                InputStream inputStream = this.getClass().getClassLoader()
                        .getResourceAsStream("template/运营数据报表模板.xlsx");
                XSSFWorkbook excel = new XSSFWorkbook(inputStream);
                ServletOutputStream out = response.getOutputStream()) {
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间:" + beginDate + "至" + endDate);
            // 获取单元格填充概览数据
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            // 填充详细数据
            List<LocalDate> dateList = getBetweenDays(beginDate, endDate);
            for (int i = 0; i < dateList.size(); i++) {
                businessDataVO = workspaceService.getBusinessData(
                        LocalDateTime.of(dateList.get(i), LocalTime.MIN),
                        LocalDateTime.of(dateList.get(i), LocalTime.MAX));
                row = sheet.getRow(i + 7);
                fillCell(row, businessDataVO, dateList.get(i));
            }
            excel.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void fillCell(XSSFRow row, BusinessDataVO businessDataVO, LocalDate date) {
        row.getCell(1).setCellValue(date.toString());
        row.getCell(2).setCellValue(businessDataVO.getTurnover());
        row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
        row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
        row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
    }
}
